package com.audaque.springboot.foshanupload.web.raspcloud.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.audaque.springboot.foshanupload.security.model.MyGrantedAuthority;
import com.audaque.springboot.foshanupload.security.model.MyUserDetail;
import com.audaque.springboot.foshanupload.web.raspcloud.entity.Role;
import com.audaque.springboot.foshanupload.web.raspcloud.entity.User;
import com.audaque.springboot.foshanupload.web.raspcloud.entity.UserRoleRel;
import com.audaque.springboot.foshanupload.web.raspcloud.mapper.UserMapper;
import com.audaque.springboot.foshanupload.web.raspcloud.service.IRoleService;
import com.audaque.springboot.foshanupload.web.raspcloud.service.IUserRoleRelService;
import com.audaque.springboot.foshanupload.web.raspcloud.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author chinaben
 * @since 2025-06-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IUserRoleRelService userRoleRelService;
    @Autowired
    private IRoleService roleService;

    public MyUserDetail getMyUserDetailByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, username);
        User user = getOne(queryWrapper);
        MyUserDetail myUserDetail = BeanUtil.toBean(user, MyUserDetail.class);
        // 根据用户名查询用户角色
        if (user != null) {
            // 1. 查询用户和角色关系
            List<UserRoleRel> userRoleRels = userRoleRelService.list(
                    new QueryWrapper<UserRoleRel>().lambda().eq(UserRoleRel::getUserId, user.getId()));
            // 2. 获取所有角色ID
            Set<Long> roleIds = userRoleRels.stream().map(UserRoleRel::getRoleId).collect(Collectors.toSet());
            // 3. 查询所有角色
            List<Role> roles = roleIds.isEmpty() ? Collections.emptyList() : roleService.listByIds(roleIds);
            // 4. 封装为权限集合
            Set<MyGrantedAuthority> authorities = roles.stream()
                    .map(role -> new MyGrantedAuthority(String.valueOf("ROLE_"+role.getId())))
                    .collect(Collectors.toSet());
            myUserDetail.setAuthorities(authorities);
        }
        return myUserDetail;
    }
}
